<template>
    <div
        class="user-page relative overflow-hidden bg-gradient-to-br from-indigo-600 via-purple-600 to-pink-600 text-white mb-8 shadow-2xl">
        <div class="container mx-auto px-4 py-8">
            <!-- 页面标题 -->
            <div class="mb-8 bg-white rounded-xl shadow-lg p-6">
                <h1 class="text-3xl font-bold text-gray-800">个人中心</h1>
                <p class="text-gray-600 mt-2">管理您的个人信息和账户设置</p>
            </div>

            <!-- 加载状态 -->
            <div v-if="loading" class="flex justify-center items-center py-12">
                <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
            </div>

            <!-- 错误状态 -->
            <div v-else-if="error" class="bg-red-50 border border-red-200 rounded-lg p-6 mb-6">
                <div class="flex items-center">
                    <div class="text-red-400 mr-3">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    </div>
                    <div>
                        <h3 class="text-red-800 font-medium">加载失败</h3>
                        <p class="text-red-600 text-sm mt-1">{{ error }}</p>
                    </div>
                </div>
            </div>

            <!-- 用户信息展示 -->
            <div v-else-if="userInfo" class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                <!-- 左侧：用户基本信息卡片 -->
                <div class="lg:col-span-1">
                    <div class="bg-white rounded-xl shadow-lg p-6">
                        <!-- 头像区域 -->
                        <div class="text-center mb-6">
                            <div
                                class="w-24 h-24 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full mx-auto flex items-center justify-center text-white text-2xl font-bold">
                                {{ userInfo.name?.charAt(0) || userInfo.username?.charAt(0) || 'U' }}
                            </div>
                            <h2 class="text-xl font-semibold text-gray-800 mt-4">{{ userInfo.name || userInfo.username
                            }}</h2>
                            <p class="text-gray-500 text-sm">@{{ userInfo.username }}</p>
                        </div>

                        <!-- 用户统计 -->
                        <div class="space-y-4">
                            <div class="flex items-center justify-between py-2 border-b border-gray-100">
                                <span class="text-gray-600">邮箱</span>
                                <span class="text-gray-800 font-medium">{{ userInfo.email }}</span>
                            </div>
                            <div class="flex items-center justify-between py-2 border-b border-gray-100">
                                <span class="text-gray-600">权限等级</span>
                                <span class="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full">
                                    {{ getAuthorityText(userInfo.authority) }}
                                </span>
                            </div>
                            <!-- <div class="flex items-center justify-between py-2 border-b border-gray-100">
                                <span class="text-gray-600">获得星星</span>
                                <span class="text-yellow-500 font-medium flex items-center">
                                    <svg class="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                                        <path
                                            d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z">
                                        </path>
                                    </svg>
                                    {{ userInfo.stars }}
                                </span>
                            </div>
                            <div class="flex items-center justify-between py-2 border-b border-gray-100">
                                <span class="text-gray-600">话题数</span>
                                <span class="text-gray-800 font-medium">{{ userInfo.commits_topic }}</span>
                            </div>
                            <div class="flex items-center justify-between py-2">
                                <span class="text-gray-600">帖子数</span>
                                <span class="text-gray-800 font-medium">{{ userInfo.commits_post }}</span>
                            </div> -->
                        </div>

                        <!-- 编辑按钮 -->
                        <button @click="toggleEditMode"
                            class="w-full mt-6 bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-lg transition-colors duration-200">
                            {{ isEditing ? '取消编辑' : '编辑信息' }}
                        </button>
                    </div>
                </div>

                <!-- 右侧：详细信息或编辑表单 -->
                <div class="lg:col-span-2">
                    <!-- 编辑模式 -->
                    <div v-if="isEditing" class="bg-white rounded-xl shadow-lg p-6">
                        <h3 class="text-xl font-semibold text-gray-800 mb-6">编辑个人信息</h3>
                        <form @submit.prevent="updateUserInfo" class="space-y-6">
                            <div>
                                <label class="text-sm font-medium text-gray-700 mb-2">姓名</label> <input
                                    v-model="editForm.name" type="text"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                    placeholder="请输入您的姓名" />
                            </div>
                            <div>
                                <label class="text-sm font-medium text-gray-700 mb-2">邮箱</label> <input
                                    v-model="editForm.email" type="email"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                    placeholder="请输入您的邮箱" />
                            </div>
                            <div class="flex space-x-4">
                                <button type="submit" :disabled="updating"
                                    class="flex-1 bg-green-500 hover:bg-green-600 disabled:bg-gray-400 text-white font-medium py-2 px-4 rounded-lg transition-colors duration-200">
                                    {{ updating ? '保存中...' : '保存更改' }}
                                </button>
                                <button type="button" @click="cancelEdit"
                                    class="flex-1 bg-gray-500 hover:bg-gray-600 text-white font-medium py-2 px-4 rounded-lg transition-colors duration-200">
                                    取消
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- 详细信息展示 -->
                    <div v-else class="space-y-6">
                        <!-- 账户信息 -->
                        <div class="bg-white rounded-xl shadow-lg p-6">
                            <h3 class="text-xl font-semibold text-gray-800 mb-4">账户信息</h3>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div class="space-y-2">
                                    <label class="text-sm font-medium text-gray-500">用户ID</label>
                                    <p class="text-gray-800">{{ userInfo.id }}</p>
                                </div>
                                <div class="space-y-2">
                                    <label class="text-sm font-medium text-gray-500">注册时间</label>
                                    <p class="text-gray-800">{{ formatDate(userInfo.createdAt) }}</p>
                                </div>
                                <div class="space-y-2">
                                    <label class="text-sm font-medium text-gray-500">最后更新</label>
                                    <p class="text-gray-800">{{ formatDate(userInfo.updatedAt) }}</p>
                                </div>
                                <!-- <div class="space-y-2">
                                    <label class="text-sm font-medium text-gray-500">账户状态</label>
                                    <span
                                        class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                        活跃
                                    </span>
                                </div> -->
                            </div>
                        </div>

                        <!-- 活动统计 -->
                        <!-- <div class="bg-white rounded-xl shadow-lg p-6">
              <h3 class="text-xl font-semibold text-gray-800 mb-4">活动统计</h3>
              <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div class="text-center">
                  <div class="text-3xl font-bold text-blue-500">{{ userInfo.stars }}</div>
                  <div class="text-sm text-gray-500 mt-1">获得星星</div>
                </div>
                <div class="text-center">
                  <div class="text-3xl font-bold text-green-500">{{ userInfo.commits_topic }}</div>
                  <div class="text-sm text-gray-500 mt-1">发布话题</div>
                </div>
                <div class="text-center">
                  <div class="text-3xl font-bold text-purple-500">{{ userInfo.commits_post }}</div>
                  <div class="text-sm text-gray-500 mt-1">发布帖子</div>
                </div>
              </div>
            </div> -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import type { User } from '~/types/user'

// 页面元信息
definePageMeta({
    middleware: 'auth'
})

// 响应式数据
const loading = ref(true)
const error = ref('')
const userInfo = ref<User | null>(null)
const isEditing = ref(false)
const updating = ref(false)

// 编辑表单数据
const editForm = ref({
    name: '',
    email: ''
})

// 获取用户信息
const fetchUserInfo = async () => {
    try {
        loading.value = true
        error.value = ''

        const response = await $fetch<{ success: boolean; data?: User; error?: string }>('/api/user/me', {
            headers: {
                'Authorization': `Bearer ${useUserStore().token}`
            }
        })

        if (response.success && response.data) {
            userInfo.value = response.data
            // 初始化编辑表单
            editForm.value = {
                name: response.data.name || '',
                email: response.data.email || ''
            }
        } else {
            error.value = response.error || '获取用户信息失败'
        }
    } catch (err: any) {
        console.error('获取用户信息失败:', err)
        error.value = err.data?.message || '获取用户信息失败'
    } finally {
        loading.value = false
    }
}

// 更新用户信息
const updateUserInfo = async () => {
    try {
        updating.value = true

        const response = await $fetch<{ success: boolean; message?: string; error?: string }>('/api/user/me', {
            method: 'PUT',
            headers: {
                'Authorization': `Bearer ${useUserStore().token}`
            },
            body: editForm.value
        })

        if (response.success) {
            // 更新本地用户信息
            await fetchUserInfo()
            isEditing.value = false

            // 显示成功消息
            console.log('用户信息更新成功')
        } else {
            console.error(response.error || '更新失败')
        }
    } catch (err: any) {
        console.error('更新用户信息失败:', err)
        console.error(err.data?.message || '更新用户信息失败')
    } finally {
        updating.value = false
    }
}

// 切换编辑模式
const toggleEditMode = () => {
    isEditing.value = !isEditing.value
    if (isEditing.value && userInfo.value) {
        editForm.value = {
            name: userInfo.value.name || '',
            email: userInfo.value.email || ''
        }
    }
}

// 取消编辑
const cancelEdit = () => {
    isEditing.value = false
    if (userInfo.value) {
        editForm.value = {
            name: userInfo.value.name || '',
            email: userInfo.value.email || ''
        }
    }
}

// 获取权限文本
const getAuthorityText = (authority: number) => {
    const authorityMap: Record<number, string> = {
        0: '普通用户',
        1: '管理员',
    }
    return authorityMap[authority] || '未知'
}

// 格式化日期
const formatDate = (date: string | Date | undefined) => {
    if (!date) return '未知'
    return new Date(date).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    })
}

// 页面加载时获取用户信息
onMounted(() => {
    fetchUserInfo()
})
</script>

<style scoped>
.user-page {
    min-height: 100vh;
}

.container {
    max-width: 1200px;
}
</style>